package logic

import (
	"common/model"
	"context"
	"errors"
	"fmt"

	product "product_server/proto"
)

func (p *ProductServer) JoinGroup(ctx context.Context, req *product.JoinGroupRequest) (*product.JoinGroupResponse, error) {
	// 获取拼团详细信息
	gb := model.GroupBuy{}
	if err := gb.Detail(int(req.GroupId)); err != nil {
		return nil, fmt.Errorf("获取拼团详细信息失败: %w", err)
	}

	// 检查拼团状态
	if gb.Status != "pending" {
		return nil, errors.New("拼团已结束")
	}

	// 检查是否是自己创建的拼团
	if int(gb.CreatorId) == int(req.Uid) {
		return nil, errors.New("不能加入自己创建的拼团")
	}

	// 检查用户是否已经在拼团中
	for _, uid := range gb.MemberIds {
		if uid == int(req.Uid) {
			return nil, errors.New("用户已在拼团中")
		}
	}

	// 检查拼团是否已满
	if gb.MaxSize <= len(gb.MemberIds) {
		return nil, errors.New("拼团已满")
	}

	// 添加用户到拼团中
	gb.MemberIds = append(gb.MemberIds, int(req.Uid))
	gb.CurrentSize++

	// 检查拼团是否满员
	if gb.MaxSize == len(gb.MemberIds) {
		gb.Status = "success"
	}

	// 更新拼团信息
	if err := gb.Update(); err != nil {
		return nil, fmt.Errorf("更新拼团信息失败: %w", err)
	}

	return &product.JoinGroupResponse{
		Success: true,
	}, nil
}
